package com.apes.fn.scm.report.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fn.scm.report.repository.SalesReportDao;
import com.apes.fn.scm.report.util.SalesReportUtils;
import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.query.SqlService;
import com.apes.framework.util.Arith;
import com.apes.framework.util.LogicalUtil;
import com.apes.framework.util.MapUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @program: apes-server
 * @description:
 * @author: czs
 * @create: 2023-02-28 13:55
 **/
@Service("salesReportService")
public class SalesReportService extends DomainService {

    @Autowired
    private SalesReportDao salesReportDao;
    @Autowired
    SqlService sqlService;

    public Object deptReport(SimpleRequest request) {
        JSONObject jo = request.getJO();

        SalesReportUtils.dateTimeToDateRange(jo,"DATE");

        JSONArray deptReports = salesReportDao.findDeptReport(jo);

        SalesReportUtils.dateTimeGetMonth(jo,"DATE","YEAR_MONTH");

        JSONArray deptTask = salesReportDao.findDeptTask(jo);

        if (deptReports.isEmpty())return deptReports;
        JSONObject deptReport = (JSONObject) deptReports.get(0);

        if (!deptTask.isEmpty())deptReport.putAll((JSONObject) deptTask.get(0));

        return SalesReportUtils.formatJsonToApp(deptReport,
                "MONTH_SALE_MONEY","累计营业额",
                "SALE_MONEY","今日营业额",
                "MONTH_PROFIT","累计毛利额",
                "VIP_AMOUNT","联盟收益",
                "BUSINESS_TASKS_AMT","目标营业额",
                "GROSS_PROFIT_TASKS_AMT","目标毛利额"
        );

    }

    public Object deptReportDetail(SimpleRequest request) {
        JSONObject jo = request.getJO();

        if ("month".equals(jo.getString("type"))){
            SalesReportUtils.dateRangChangeToFirstDayAndLastDay(jo);
        }
        JSONArray deptReports = salesReportDao.findDeptReportDetailNoFormat(jo);

        if (deptReports.isEmpty())deptReports.add(new JSONObject());
        JSONObject deptReport = (JSONObject) deptReports.get(0);

        JSONObject result = SalesReportUtils.formatJsonToApp(deptReport,
                "SALE_MONEY", "营业额(元)",
                "PROFIT", "毛利额(元)",
                "PROFIT_R", "毛利率",
                "VIP_AMOUNT","联盟收益",
                "ADVANCE", "预收",
                "COST", "成本额",
                "TIMES", "进店台次"
        );
        //不含预收
        if (!jo.getBoolean("ADVANCE")){
            SalesReportUtils.calculateResultJsonPercent(result,
                    "SALE_MONEY","ADVANCE","-","SALE_MONEY","营业额(元)",
                    "PROFIT","ADVANCE","-","PROFIT","毛利额(元)",
                    "PROFIT","SALE_MONEY","/","PROFIT_R","毛利率"
            );
        }
        //月数据需包含
        if ("month".equals(jo.getString("type"))){
            SalesReportUtils.dateTimeGetMonth(jo,"DATE_START","YEAR_MONTH");

            JSONArray deptTasks = salesReportDao.findDeptTask(jo);
            //设置目标
            findDeptTask(result, deptTasks);
        }



        return result;

    }

    private void findDeptTask(JSONObject result, JSONArray deptTasks) {
        boolean empty = deptTasks.isEmpty();
        if (empty)deptTasks.add(new JSONObject());
//            if (deptTasks.isEmpty())return result;
        JSONObject deptTask = (JSONObject) deptTasks.get(0);


        if (empty){
            result.put("SALE_MONEY_ACHIEVING_RATE", MapUtil.mapper("name", "营业额达成率", "value","未设目标"));
            result.put("BUSINESS_TASKS_AMT", MapUtil.mapper("name", "目标营业额", "value","--"));
            result.put("PROFIT_ACHIEVING_RATE", MapUtil.mapper("name", "毛利额达成率", "value","未设目标"));
            result.put("GROSS_PROFIT_TASKS_AMT", MapUtil.mapper("name", "目标毛利额", "value","--"));
        }else {
            result.putAll(SalesReportUtils.formatJsonToApp(deptTask,
                    "BUSINESS_TASKS_AMT","目标营业额",
                    "GROSS_PROFIT_TASKS_AMT","目标毛利额"
            ));
            SalesReportUtils.calculateResultJsonPercent(result,
                    "SALE_MONEY","BUSINESS_TASKS_AMT","/","SALE_MONEY_ACHIEVING_RATE","营业额达成率",
                    "PROFIT","GROSS_PROFIT_TASKS_AMT","/","PROFIT_ACHIEVING_RATE","毛利额达成率"
            );
            result.put("SALE_MONEY_ACHIEVING_RATE", MapUtil.mapper("name", "营业额达成率", "value",SalesReportUtils.getResultJsonValue(result,"SALE_MONEY_ACHIEVING_RATE")+"%"));
            result.put("PROFIT_ACHIEVING_RATE", MapUtil.mapper("name", "毛利额达成率", "value",SalesReportUtils.getResultJsonValue(result,"PROFIT_ACHIEVING_RATE")+"%"));
        }
    }

    public Object deptReportSalesTrend(SimpleRequest request){
        JSONObject jo = request.getJO();
        JSONObject result = new JSONObject();
        JSONArray deptReports = new JSONArray();

        if ("month".equals(jo.getString("type"))){
            SalesReportUtils.dateRangChangeToFirstDayAndLastDay(jo);
            deptReports = salesReportDao.findDeptReportDetail(jo);

        }else if ("day".equals(jo.getString("type"))){
            deptReports = salesReportDao.findDeptReport(jo);
        }else if ("week".equals(jo.getString("type"))){
            SalesReportUtils.dateTimeGetWeekRange(jo,"DATE");
            deptReports = salesReportDao.findDeptReportByWeek(jo);
        }

        if (!jo.getBoolean("ADVANCE")){
            result = SalesReportUtils.jsonArrayToLineStack(deptReports,jo,"DATE_OF_STATISTICS",
                    "SALE_MONEY_EX_ADVANCE", "营业额","0",
                    "VIP_AMOUNT", "联盟收益","0",
//                    "DATE_OF_STATISTICS", "日期","DATE_OF_STATISTICS",
                    "PROFIT_EX_ADVANCE", "毛利额","0", "TIMES", "车流量","0");
//            SalesReportUtils.changeTargetName(result,"SALE_MONEY_EX_ADVANCE","SALE_MONEY","PROFIT_EX_ADVANCE","PROFIT");
        }else {
            result = SalesReportUtils.jsonArrayToLineStack(deptReports,jo,"DATE_OF_STATISTICS",
                    "SALE_MONEY", "营业额","0",
                    "VIP_AMOUNT", "联盟收益","0",
//                    "DATE_OF_STATISTICS", "日期","DATE_OF_STATISTICS",
                    "PROFIT", "毛利额","0", "TIMES", "车流量","0");
        }
        JSONArray series = result.getJSONArray("series");
        List sortResult = new ArrayList();
        Object profit = series.stream().filter(o -> ((JSONObject) o).getString("name").equals("毛利额")).findFirst().orElse(null);
        Object sale_money = series.stream().filter(o -> ((JSONObject) o).getString("name").equals("营业额")).findFirst().orElse(null);
        Object profit_r_min = series.stream().filter(o -> ((JSONObject) o).getString("name").equals("车流量")).findFirst().orElse(null);
        sortResult.add(0,profit);
        sortResult.add(1,sale_money);
        sortResult.add(2,profit_r_min);
        result.put("series",sortResult);

        return result;
    }

    public Object businessAnalyseReportTrend(SimpleRequest request){
        JSONObject jo = request.getJO();
        JSONObject result = new JSONObject();
        JSONArray deptReports = new JSONArray();

        if ("month".equals(jo.getString("type"))){
            SalesReportUtils.dateRangChangeToFirstDayAndLastDay(jo);
            deptReports = salesReportDao.findDeptReportDetail(jo);

        }else if ("day".equals(jo.getString("type"))){
            deptReports = salesReportDao.findDeptReport(jo);
        }else if ("week".equals(jo.getString("type"))){
            SalesReportUtils.dateTimeGetWeekRange(jo,"DATE");
            deptReports = salesReportDao.findDeptReportByWeek(jo);
        }

        if (!jo.getBoolean("ADVANCE")) {
            result = SalesReportUtils.jsonArrayToLineOrBarStack(deptReports, jo, "DATE_OF_STATISTICS", "SALE_MONEY_EX_ADVANCE", "营业额", "bar", "0", "PROFIT_EX_ADVANCE", "毛利额", "bar", "0", "PROFIT_R_MIN", "毛利率", "line", "0");
//            SalesReportUtils.changeTargetName(result,"SALE_MONEY_EX_ADVANCE","SALE_MONEY","PROFIT_EX_ADVANCE","PROFIT");
        } else {
            result = SalesReportUtils.jsonArrayToLineOrBarStack(deptReports, jo, "DATE_OF_STATISTICS", "SALE_MONEY", "营业额", "bar", "0", "PROFIT", "毛利额", "bar", "0", "PROFIT_R_MIN", "毛利率", "line", "0");
        }
        JSONArray series = result.getJSONArray("series");
        List sortResult = new ArrayList();
        Object profit = series.stream().filter(o -> ((JSONObject) o).getString("name").equals("毛利额")).findFirst().orElse(null);
        Object sale_money = series.stream().filter(o -> ((JSONObject) o).getString("name").equals("营业额")).findFirst().orElse(null);
        Object profit_r_min = series.stream().filter(o -> ((JSONObject) o).getString("name").equals("毛利率")).findFirst().orElse(null);
        sortResult.add(0,profit);
        sortResult.add(1,sale_money);
        sortResult.add(2,profit_r_min);
        result.put("series",sortResult);
        return result;
    }

    public Object businessAnalyseReport(SimpleRequest request){
        JSONObject jo = request.getJO();
        JSONArray result = new JSONArray();
        JSONObject sale = new JSONObject();
        JSONObject cost = new JSONObject();
        JSONObject clientUnit = new JSONObject();
        JSONObject profit = new JSONObject();
        JSONObject profitPercent = new JSONObject();
        JSONArray jsonArray ;
        if ("month".equals(jo.getString("type"))){
            SalesReportUtils.dateRangChangeToFirstDayAndLastDay(jo);
            jsonArray = salesReportDao.businessAnalyseReportDetailNoType(jo,"MM");
            if (jsonArray.isEmpty())jsonArray.add(new JSONObject(MapUtil.mapper("AMT",0)));
            sale = SalesReportUtils.filterJson((JSONObject) jsonArray.get(0),
                    "SALE_MONEY", "AMT",
                    "SALE_MONEY", "SALE_MONEY",
                    "BUSINESS_AMT_PERCENT", "AMT_PERCENT",
                    "SALE_MONEY_MOM_R", "MOM_R",
                    "SALE_MONEY_YOY_R", "YOY_R",
                    "SALES_TYPE_AVG", "TYPE_AVG",
                    "SALES_TYPE_DIFF", "TYPE_DIFF",
                    "SALE_MONEY_YOY_R", "YOY_R",
                    "SALES_TYPE_BEST", "TYPE_BEST",
                    "SALES_TYPE_BEST_DIFF", "TYPE_BEST_DIFF",
                    "SALES_AREA_AVG", "AREA_AVG",
                    "SALES_AREA_DIFF", "AREA_DIFF",
                    "SALES_AREA_BEST", "AREA_BEST",
                    "SALES_AREA_BEST_DIFF", "AREA_BEST_DIFF"
            );
            sale.put("TYPE","SALE");
            result.add(sale);
            cost = SalesReportUtils.filterJson((JSONObject) jsonArray.get(0),
                    "COST_AMT", "AMT",
                    "COST_MOM_R", "MOM_R",
                    "VIP_AMOUNT", "VIP_AMOUNT",
                    "COST_YOY_R", "YOY_R"
            );
            cost.put("TYPE","COST");
            result.add(cost);
            clientUnit = SalesReportUtils.filterJson((JSONObject) jsonArray.get(0),
                    "CLIENT_UNIT", "AMT",
                    "CLIENT_UNIT_MOM_R", "MOM_R",
                    "CLIENT_UNIT_YOY_R", "YOY_R"
            );
            clientUnit.put("TYPE","CLIENT_UNIT");
            result.add(clientUnit);
            profit = SalesReportUtils.filterJson((JSONObject) jsonArray.get(0),
                    "PROFIT_AMT", "AMT",
                    "GROSS_PROFIT_AMT_PERCENT", "AMT_PERCENT",
                    "PROFIT_MOM_R", "MOM_R",
                    "PROFIT_YOY_R", "YOY_R",
                    "PROFIT_TYPE_AVG", "TYPE_AVG",
                    "PROFIT_TYPE_DIFF", "TYPE_DIFF",
                    "PROFIT_TYPE_BEST", "TYPE_BEST",
                    "PROFIT_TYPE_BEST_DIFF", "TYPE_BEST_DIFF",
                    "PROFIT_AREA_AVG", "AREA_AVG",
                    "PROFIT_AREA_DIFF", "AREA_DIFF",
                    "PROFIT_AREA_BEST", "AREA_BEST",
                    "PROFIT_AREA_BEST_DIFF", "AREA_BEST_DIFF",
                    "PROFIT_TYPE_AVG", "TYPE_AVG"
            );
            profit.put("TYPE","PROFIT");
            result.add(profit);
            profitPercent = SalesReportUtils.filterJson((JSONObject) jsonArray.get(0),
                    "PROFIT_R", "AMT",
                    "GROSS_PROFIT_AMT_PERCENT", "AMT_PERCENT",
                    "PROFIT_R_MOM_R", "MOM_R",
                    "PROFIT_R_YOY_R", "YOY_R",
                    "PROFIT_R_TYPE_AVG", "TYPE_AVG",
                    "PROFIT_R_TYPE_DIFF", "TYPE_DIFF",
                    "PROFIT_R_TYPE_BEST", "TYPE_BEST",
                    "PROFIT_R_TYPE_BEST_DIFF", "TYPE_BEST_DIFF",
                    "PROFIT_R_AREA_AVG", "AREA_AVG",
                    "PROFIT_R_AREA_DIFF", "AREA_DIFF",
                    "PROFIT_R_AREA_BEST", "AREA_BEST",
                    "PROFIT_R_AREA_BEST_DIFF", "AREA_BEST_DIFF"
            );
            profitPercent.put("TYPE","PROFIT_RATE");
            result.add(profitPercent);
        }else if("week".equals(jo.getString("type"))){
            jsonArray = salesReportDao.businessAnalyseReportDetailNoType(jo,"iw");
            if (jsonArray.isEmpty())jsonArray.add(new JSONObject(MapUtil.mapper("AMT",0)));
            sale = SalesReportUtils.filterJson((JSONObject) jsonArray.get(0),
                    "SALE_MONEY", "AMT",
                    "SALES_TYPE_AVG", "TYPE_AVG"
            );
            sale.put("TYPE","SALE");
            result.add(sale);
            cost = SalesReportUtils.filterJson((JSONObject) jsonArray.get(0),
                    "VIP_AMOUNT", "VIP_AMOUNT",
                    "COST_AMT","AMT"
            );
            cost.put("TYPE","COST");
            result.add(cost);
            clientUnit = SalesReportUtils.filterJson((JSONObject) jsonArray.get(0),
                    "CLIENT_UNIT","AMT"
            );
            clientUnit.put("TYPE","CLIENT_UNIT");
            result.add(clientUnit);
            profit = SalesReportUtils.filterJson((JSONObject) jsonArray.get(0),
                    "PROFIT_AMT","AMT"
            );
            profit.put("TYPE","PROFIT");
            result.add(profit);
            profitPercent = SalesReportUtils.filterJson((JSONObject) jsonArray.get(0),
                    "PROFIT_R","AMT"
            );
            profitPercent.put("TYPE","PROFIT_RATE");
            result.add(profitPercent);
        }else {

            jsonArray = salesReportDao.businessAnalyseReportDetailNoType(jo,"YYYY");
            if (jsonArray.isEmpty())jsonArray.add(new JSONObject(MapUtil.mapper("AMT",0)));
            sale = SalesReportUtils.filterJson((JSONObject) jsonArray.get(0),
                    "SALE_MONEY", "AMT",
                    "VIP_AMOUNT", "VIP_AMOUNT",
                    "SALES_TYPE_AVG", "TYPE_AVG"
            );
            sale.put("TYPE","SALE");
            result.add(sale);
            cost = SalesReportUtils.filterJson((JSONObject) jsonArray.get(0),
                    "VIP_AMOUNT", "VIP_AMOUNT",
                    "COST_AMT","AMT"
            );
            cost.put("TYPE","COST");
            result.add(cost);
            clientUnit = SalesReportUtils.filterJson((JSONObject) jsonArray.get(0),
                    "CLIENT_UNIT","AMT"
            );
            clientUnit.put("TYPE","CLIENT_UNIT");
            result.add(clientUnit);
            profit = SalesReportUtils.filterJson((JSONObject) jsonArray.get(0),
                    "PROFIT_AMT","AMT"
            );
            profit.put("TYPE","PROFIT");
            result.add(profit);
            profitPercent = SalesReportUtils.filterJson((JSONObject) jsonArray.get(0),
                    "PROFIT_R","AMT"
            );
            profitPercent.put("TYPE","PROFIT_RATE");
            result.add(profitPercent);
        }

        return result;
    }

    public Object businessAnalyseSalesComparison(SimpleRequest request) throws Exception {
        JSONObject jo = request.getJO();
        JSONObject result = new JSONObject();
        JSONArray jsonArray ;
        JSONArray dateRankType ;
        JSONArray dateRank = new JSONArray() ;
//        Date nowDate = SpringManager.getBean(OilCardInfoService.class).getNowDate();
//        jo.put("DATE", new SimpleDateFormat("YYYY-MM-DD").format(nowDate));
//        SalesReportUtils.dateTimeToDateRange(jo,"DATE");
        if ("month".equals(jo.getString("type"))){
            SalesReportUtils.dateRangChangeToFirstDayAndLastDay(jo);
            jsonArray = salesReportDao.businessAnalyseReportDetail(jo,"MM");
            dateRankType = salesReportDao.findDateRankMonth(jo);
        }else if ("week".equals(jo.getString("type"))){
            SalesReportUtils.dateTimeGetWeekRange(jo,"DATE");
            jsonArray = salesReportDao.businessAnalyseReportDetailByWeek(jo,"DD");
            dateRankType = salesReportDao.findDateRankWeek(jo);
        }else {
            jsonArray = salesReportDao.businessAnalyseReportDetail(jo,"DD");
//            SalesReportUtils.dateRangeFindWeekRange(jo);
            dateRankType = salesReportDao.findDateRankDay(jo);
        }
        JSONObject jsonObject = SalesReportUtils.jsonArrayToLineStack(jsonArray,jo,"DATE_OF_STATISTICS",
                "SALE_MONEY", "本店数据","0",
                "SALE_CIRCLE_AVG_DIFF", "商圈差异","0",
                "BUSINESS_CIRCLE_NAME", "商圈名称","0",
                "VIP_AMOUNT", "联盟收益","0",
//                "SALES_AREA_AVG", "战区均值",
//                "SALES_TYPE_RANK_COMMENT", "排名评语",
//                "TYPE_RANK_TOTAL", "营业额排名总数",
//                "SALES_TYPE_RANK", "营业额排名",
                "SALES_AREA_AVG", "战区均值","0",
                "SALES_TYPE_AVG", "同类均值","0");
        for (Object o : dateRankType) {
            JSONObject json = (JSONObject)o;
            dateRank.add( SalesReportUtils.formatJsonToApp(json,
                    "SALE_MONEY_MOM", "环比",
                    "SALES_TYPE_AVG", "同类均值",
                    "SALES_TYPE_RANK", "同类排名",
                    "TYPE_RANK_TOTAL", "同类排名总数",
                    "SALES_TYPE_RANK_COMMENT", "排名评语",
                    "CHAR_DATE", "时间区间"
            ));
        }

        SalesReportUtils.changeVal2ToVal1Name(jsonObject,true,"商圈差异","商圈名称");

        jsonObject.put("dateRank",dateRank);
        return jsonObject;

    }
    public Object businessAnalyseServeTypeRank(SimpleRequest request){
        JSONObject jo = request.getJO();
        JSONArray resultArray = new JSONArray();
        SalesReportUtils.dateTimeToDateRange(jo,"DATE");
        SalesReportUtils.dateRangChangeToFirstDayAndLastDay(jo);
        JSONArray monthServeTypeDetail = salesReportDao.findMonthServeTypeDetail(jo);
        for (Object o : monthServeTypeDetail) {
            JSONObject jsonObject = (JSONObject)o;
            resultArray.add(SalesReportUtils.formatJsonToApp(jsonObject,
                    "SALE_MONEY","金额",
                    "TIMES","台次",
                    "PROFIT_R","毛利率",
                    "SALE_RANK","排名",
                    "SALE_MONEY_MON","环比",
                    "SALE_MONEY_YOY","同比",
                    "TOTAL_SALE_MONEY_R","占比",
                    "SERVE_TYPE_NAME","服务类型"
                    ));
        }
        return resultArray;
    }

    /**
     * 提成产值
     * @param request
     * @return
     */
    public Object gdpAndDeductDetail(SimpleRequest request){
        JSONObject jo = request.getJO();
        JSONObject result = new JSONObject();
        if ("month".equals(jo.getString("type"))){
            SalesReportUtils.dateRangChangeToFirstDayAndLastDay(jo);
            JSONArray jsonArray = salesReportDao.gdpAndDeductByMonth(jo);
            JSONObject jsonObject = jsonArray.isEmpty()?new JSONObject():jsonArray.getJSONObject(0);
            result = SalesReportUtils.formatJsonToApp(jsonObject,
                    "PERSON_GDP", "预估产值",
                    "PERSON_GDP_MOM", "环比",
                    "SALES_GDP", "销售产值(元)",
                    "WORK_GDP", "施工产值(元)",
                    "PERSON_DEDUCT", "预估提成",
                    "PERSON_DEDUCT_MOM", "环比",
                    "SALES_DEDUCT", "销售提成(元)",
                    "WORK_DEDUCT", "施工提成(元)",
                    "PROFIT", "预估毛利",
                    "PROFIT_MOM", "环比",
                    "DEPT_NAME", "门店名称",
                    "DEPT_ID", "门店编码"
            );
        }else {

            JSONArray jsonArray = salesReportDao.gdpAndDeductByDay(jo);
            JSONObject jsonObject = jsonArray.isEmpty()?new JSONObject():jsonArray.getJSONObject(0);
            result = SalesReportUtils.formatJsonToApp(jsonObject,
                    "PERSON_GDP", "预估产值",
                    "SALES_GDP", "销售产值(元)",
                    "WORK_GDP", "施工产值(元)",
                    "PERSON_DEDUCT", "预估提成",
                    "SALES_DEDUCT", "销售提成(元)",
                    "WORK_DEDUCT", "施工提成(元)",
                    "PROFIT", "预估毛利",
                    "DEPT_NAME", "门店名称",
                    "DEPT_ID", "门店编码"
            );
//            SalesReportUtils.dateTimeToDateNext(jo,"DATE_END");
        }

        JSONArray bpDetail = salesReportDao.findBPDetail(jo);
        jo.put("SERVE_TYPE_ID","001");
        JSONArray typeTimes = salesReportDao.findTypeTimes(jo);
        Double paintNumber = Arith.round(SalesReportUtils.calculateResultArraySum(bpDetail, "SPRAY_PAINT_NUMBER", "+"),2);
        result.put("PAINT_NUMBER",MapUtil.mapper("name","喷漆幅数","value",paintNumber));
        JSONObject jsonObject = SalesReportUtils.formatJsonToApp((JSONObject) typeTimes.get(0), "TIMES", "洗车台次");
        result.putAll(jsonObject);
        return result;
    }

    /**
     * 人员/岗位毛利排名
     * @param request
     * @return
     */
    public Object salesReportProfitRank(SimpleRequest request){
        JSONObject jo = request.getJO();
        JSONObject result = new JSONObject();
        if ("month".equals(jo.getString("dateType"))){
            jo.put("FORMAT","MM");
//            SalesReportUtils.dateTimeToDateRange(jo,"DATE");
            SalesReportUtils.dateRangChangeToFirstDayAndLastDay(jo);
        }else if("day".equals(jo.getString("dateType"))){
            jo.put("FORMAT","DD");
//            SalesReportUtils.dateTimeToDateRange(jo,"DATE");
        }else if("week".equals(jo.getString("dateType"))){
            jo.put("FORMAT","iw");
        }else {
            jo.put("FORMAT","yyyy");
        }
        JSONArray jsonArray ;
        JSONArray rankArray = new JSONArray() ;
        JSONObject pie = new JSONObject() ;
        switch (jo.getString("rankType")){
            case "person":
                jsonArray = salesReportDao.salesReportProfitRankByPerson(jo);
                for (Object o : jsonArray) {
                    JSONObject jsonObject = (JSONObject) o;
                    JSONObject json = SalesReportUtils.formatJsonToApp(jsonObject,
                            "PERSON_NAME", "人员名称",
                            "POST_NAME", "岗位名称",
                            "CLIENT_UNIT_PRICE", "客单价",
                            "TIMES", "台次",
                            "RANK", "名次",
                            "PROFIT_PROPORTION", "占比",
                            "PROFIT_MOM", "环比",
                            "PROFIT", "毛利额"
                    );
                    rankArray.add(json);
                }
                pie = SalesReportUtils.drawPie(rankArray, "PROFIT_PROPORTION", "PROFIT", "PERSON_NAME");
                break;
            case "post":
                jsonArray = salesReportDao.salesReportProfitRankByPost(jo);
                for (Object o : jsonArray) {
                    JSONObject jsonObject = (JSONObject) o;
                    JSONObject json = SalesReportUtils.formatJsonToApp(jsonObject,
                            "POST_NAME", "岗位名称",
                            "TIMES", "台次",
                            "RANK", "名次",
                            "PROFIT_PROPORTION", "占比",
                            "PROFIT_MOM", "环比",
                            "PROFIT", "毛利额"
                    );
                    rankArray.add(json);
                }
                pie = SalesReportUtils.drawPie(rankArray, "PROFIT_PROPORTION", "PROFIT", "POST_NAME");
                break;
                default:
                    throw new RuntimeException("未知类型:"+jo.getString("rankType"));
        }


        result.put("rankArray",rankArray);
        result.put("pie",pie);

    return result;
    }

    public Object findCategoryServeType(SimpleRequest request){
        JSONArray categoryServeType = salesReportDao.findByCategoryServeType(request.getJO());
        return new PageImpl(categoryServeType, PageRequest.of(0, 50), categoryServeType.size());

    }

    //以上是APP查询接口
    //以下是提供页面查询


    public Map categoryAnalyseGdpDetail(SimpleRequest request){
        JSONObject jo = request.getJO();
        JSONObject model = getConditionModel(jo);
        com.apestech.framework.json.JSONArray queryResult = new com.apestech.framework.json.JSONArray();
        String serve_type = model.getString("SERVE_TYPE")==null?" ":model.getString("SERVE_TYPE");
        switch (serve_type){
            case " ":
            case "MoneyIncome":
                queryResult.addAll(sqlService.queryId("categoryAnalyse.moneyIncome", new com.apestech.framework.json.JSONObject(model)));
                if (!" ".equals(serve_type))break;
            case "UsedCar":
                queryResult.addAll(sqlService.queryId("categoryAnalyse.usedCar", new com.apestech.framework.json.JSONObject(model)));
                if (!" ".equals(serve_type))break;
            case"定损":
                queryResult.addAll(sqlService.queryId("categoryAnalyse.loss", new com.apestech.framework.json.JSONObject(model)));
                if (!" ".equals(serve_type))break;
            case "PolicyInformation":
                queryResult.addAll(sqlService.queryId("categoryAnalyse.policyInformation", new com.apestech.framework.json.JSONObject(model)));
                if (!" ".equals(serve_type)) break;
                default:
                    queryResult.addAll(sqlService.queryId("categoryAnalyse.gdpDetail", new com.apestech.framework.json.JSONObject(model)));
//                    queryResult.addAll(sqlService.queryId("categoryAnalyse.vip", new com.apestech.framework.json.JSONObject(model)));
                    break;
        }

        int size = queryResult.size();
        return MapUtil.mapper(
                "content", queryResult,
                "total", size,
                "size", size
        );
    }

    public Map saleMoneyDetail(SimpleRequest request){
        JSONObject jo = request.getJO();
        JSONObject model = getConditionModel(jo);
        String showType = model.getString("_showType");
        if (showType.equals("1")){
            SalesReportUtils.dateTimeGetMonth(model,"CREATE_DATE_S","CREATE_DATE");
        }else if (showType.equals("0")){
            SalesReportUtils.getNextDate(model,"CREATE_DATE_S","CREATE_DATE");
            model.put("CREATE_DATE_E",model.get("CREATE_DATE_S"));
        }
//        JSONArray salesAmountDetail = salesReportDao.findSalesAmountDetail(model);
        JSONArray salesAmountDetail = salesReportDao.findSalesAmountDetail(model);

        int size = salesAmountDetail.size();
        return MapUtil.mapper(
                "content", salesAmountDetail,
                "total", size,
                "size", size
        );
    }

    private JSONObject getConditionModel(JSONObject jo) {
        JSONObject condition = jo.getJSONObject("condition");
        List<Map> filters = (List<Map>) condition.get("filters");
        JSONObject model = new JSONObject();
        filters.forEach(filter -> {
            model.put((String) filter.get("field"), filter.get("value"));
        });
        return model;
    }

    public Map costDetail(SimpleRequest request){
        JSONObject jo = request.getJO();
        JSONObject model = getConditionModel(jo);
        String showType = model.getString("_showType");
        if (showType.equals("1")){
            SalesReportUtils.dateTimeGetMonth(model,"CREATE_DATE_S","CREATE_DATE");
        }else if (showType.equals("0")){
            SalesReportUtils.getNextDate(model,"CREATE_DATE_S","CREATE_DATE");
            model.put("CREATE_DATE_E",model.get("CREATE_DATE_S"));
        }
        JSONArray salesAmountDetail = salesReportDao.findCostDetail(model);

        int size = salesAmountDetail.size();
        return MapUtil.mapper(
                "content", salesAmountDetail,
                "total", size,
                "size", size
        );
    }
    public Map gdpDetail(SimpleRequest request){
        JSONObject jo = request.getJO();
        JSONObject model = getConditionModel(jo);
        String showType = model.getString("_showType");
        if (showType.equals("1")){
            SalesReportUtils.dateTimeGetMonth(model,"CREATE_DATE_S","CREATE_DATE");
        }else if (showType.equals("0")){
            SalesReportUtils.getNextDate(model,"CREATE_DATE_S","CREATE_DATE");
        }
        JSONArray salesAmountDetail = salesReportDao.findGdpDetail(model);

        int size = salesAmountDetail.size();
        return MapUtil.mapper(
                "content", salesAmountDetail,
                "total", size,
                "size", size
        );
    }
    public com.apestech.framework.json.JSONObject reportByDay(SimpleRequest request) throws Exception {
        JSONObject jo = request.getJO();

        return com.apestech.framework.json.JSON.toJSON(jo.toJSONString());
    }

    public com.apestech.framework.json.JSONObject reportByMonth(SimpleRequest request) throws Exception {
        JSONObject jo = request.getJO();

        return com.apestech.framework.json.JSON.toJSON(jo.toJSONString());
    }

    public com.apestech.framework.json.JSONObject reportBySummary(SimpleRequest request) throws Exception {
        JSONObject jo = request.getJO();
        JSONArray condition = jo.getJSONArray("condition");
        JSONArray newCondition = new JSONArray();
        if (condition != null) {
            for (int i = 0; i < condition.size(); i++) {
                if (LogicalUtil.notIn(condition.getJSONObject(i).getString("field"),"MONTH_OF_STATISTICS","TYPE_DEPT")){
                    newCondition.add(condition.getJSONObject(i));
                }

                if ("DATE_OF_STATISTICS".equals(condition.getJSONObject(i).getString("field"))){
                    JSONObject json = new JSONObject();
                    if("GTE".equals(condition.getJSONObject(i).getString("operator"))){
                        json.put("field","DONE_DATE_START");
                        json.put("operator","EQ");
                        json.put("value",condition.getJSONObject(i).getString("value"));
                        json.put("type","date");
                        newCondition.add(json);
                    }else if("LTE".equals(condition.getJSONObject(i).getString("operator"))){
                        json.put("field","DONE_DATE_END");
                        json.put("operator","EQ");
                        json.put("value",condition.getJSONObject(i).getString("value"));
                        json.put("type","date");
                        newCondition.add(json);
                    }
                }

            }
            jo.put("condition", newCondition);
        }

        return com.apestech.framework.json.JSON.toJSON(jo.toJSONString());
    }
    public com.apestech.framework.json.JSONObject categoryAnalyseReportByDay(SimpleRequest request) throws Exception {
        JSONObject jo = request.getJO();

        return com.apestech.framework.json.JSON.toJSON(jo.toJSONString());
    }

    public com.apestech.framework.json.JSONObject categoryAnalyseReportByMonth(SimpleRequest request) throws Exception {
        JSONObject jo = request.getJO();

        return com.apestech.framework.json.JSON.toJSON(jo.toJSONString());
    }

    public com.apestech.framework.json.JSONObject categoryAnalyseReportBySummary(SimpleRequest request) throws Exception {
        JSONObject jo = request.getJO();
        JSONArray condition = jo.getJSONArray("condition");
        JSONArray newCondition = new JSONArray();
        if (condition != null) {
            for (int i = 0; i < condition.size(); i++) {
                if (!"MONTH_OF_STATISTICS".equals(condition.getJSONObject(i).getString("field"))){
                    newCondition.add(condition.getJSONObject(i));
                }if ("DATE_OF_STATISTICS".equals(condition.getJSONObject(i).getString("field"))){
                    JSONObject json = new JSONObject();
                    if("GTE".equals(condition.getJSONObject(i).getString("operator"))){
                        json.put("field","DONE_DATE_START");
                        json.put("operator","EQ");
                        json.put("value",condition.getJSONObject(i).getString("value"));
                        json.put("type","date");
                        newCondition.add(json);
                    }else if("LTE".equals(condition.getJSONObject(i).getString("operator"))){
                        json.put("field","DONE_DATE_END");
                        json.put("operator","EQ");
                        json.put("value",condition.getJSONObject(i).getString("value"));
                        json.put("type","date");
                        newCondition.add(json);
                    }
                }

            }
            jo.put("condition", newCondition);
        }

        return com.apestech.framework.json.JSON.toJSON(jo.toJSONString());
    }


    }
